#include "logwindow.h"
#include <QMessageBox>
#include "flightscheckwindow.h"
#include "interfacemanager.h"
#include "system.h"
#include "ui_logwindow.h"
#include "models.h"

LogWindow::LogWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::LogWindow)
    , manager(new QNetworkAccessManager(this))
{
    ui->setupUi(this);
}
int LogWindow::userId = 0;
QString LogWindow::username ;     // 初始化用户名
QString LogWindow::email ;        // 初始化用户邮箱
QString LogWindow::phone;        // 初始化用户电话
int LogWindow::age ;              // 初始化用户年龄
QString LogWindow::gender ;       // 初始化用户性别
QString LogWindow::idNumber ;     // 初始化身份证号
int LogWindow::userLevel ;        // 初始化用户等级

void LogWindow::on_toBetaButton_clicked()
{
    //跳转first界面
    InterfaceManager::instance()->switchToPage("/MainWindow/First");
}

LogWindow::~LogWindow()
{
    delete ui;
}

void LogWindow::on_toErollbutton_clicked()
{
    //点击跳转注册界面
    InterfaceManager::instance()->switchToPage("/MainWindow/First/Enroll");
}

void LogWindow::on_LogButton_clicked()
{
    // 从 QLineEdit 控件读取数据
    QString email = ui->UserEmailEdit->text();
    QString password = ui->PasswordEdit->text();

    // 创建一个 JSON 对象，封装请求体
    QJsonObject json;
    json["email"] = email;
    json["password"] = password;
    qDebug() << "Preparing request data:" << json;

    // 将 JSON 对象转换为 JSON 文档
    QJsonDocument doc(json);
    QByteArray data = doc.toJson();

    // 设置请求头
    QNetworkRequest request(QUrl("http://127.0.0.1:8080/api/users/login")); // 替换为你的 API URL
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

    // 发送 POST 请求
    QNetworkReply *reply = manager->post(request, data);

    // 连接请求完成信号
    connect(reply, &QNetworkReply::finished, this, &LogWindow::onLoginRequestFinished);
}

void LogWindow::onLoginRequestFinished()
{
    QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender());

    // 如果请求失败，输出错误信息
    if (reply->error() != QNetworkReply::NoError) {
        QString errorString = reply->errorString(); // 获取错误信息
        qDebug() << "Request failed with error:" << errorString;
        QMessageBox::critical(this, "Error", "Login request failed: " + errorString);
        reply->deleteLater();
        return;
    }

    // 请求成功，处理响应数据
    QByteArray response = reply->readAll();
    QJsonDocument doc = QJsonDocument::fromJson(response);
    QJsonObject jsonResponse = doc.object();

    // 处理响应
    int code = jsonResponse["code"].toInt();
    if (code == 200) {
        // 登录成功
        QMessageBox::information(this, "Success", "Login successful!");

        LogWindow::userId = jsonResponse["data"].toObject()["id"].toInt();  // 设置用户ID
        LogWindow::username = jsonResponse["data"].toObject()["username"].toString();  // 设置用户名
        LogWindow::email = jsonResponse["data"].toObject()["email"].toString();  // 设置用户邮箱
        LogWindow::phone = jsonResponse["data"].toObject()["phone"].toString();  // 设置用户电话
        LogWindow::age = jsonResponse["data"].toObject()["age"].toInt();  // 设置用户年龄
        LogWindow::gender = jsonResponse["data"].toObject()["gender"].toString();  // 设置用户性别
        LogWindow::idNumber = jsonResponse["data"].toObject()["idNumber"].toString();  // 设置身份证号
        LogWindow::userLevel = jsonResponse["data"].toObject()["userLevel"].toInt();  // 设置用户等级

        QString userRole = jsonResponse["data"].toObject()["role"].toString();

        // 显示或使用这些数据
        qDebug() << "User ID: " << userId;
        qDebug() << "Username: " << username;
        qDebug() << "Email: " << email;
        qDebug() << "Role: " << userRole;

        //InterfaceManager::instance()->unregisterPage("/MainWindow/First/FlightCheck");
        FlightsCheckWindow *flightscheck1 = new FlightsCheckWindow();
        InterfaceManager::instance()->registerPage("/MainWindow/First/FlightCheck", flightscheck1);
        InterfaceManager::instance()->log_index = 1;
        InterfaceManager::instance()
            ->m_pages["/MainWindow/First/FlightCheck"]
            ->findChild<QStackedWidget *>("stackedWidget")
            ->setCurrentIndex(InterfaceManager::instance()->log_index);

        InterfaceManager::instance()->switchToPage("/MainWindow/First/FlightCheck");
    } else {
        // 登录失败
        QString errorMessage = jsonResponse["message"].toString();
        QMessageBox::warning(this, "Error", "Login failed: " + errorMessage);
        qDebug() << "Error Message: " << errorMessage;
    }

    // 释放资源
    reply->deleteLater();
}
